<?php
/**
 * 礼卡管理Controller
 * Created by PhpStorm.
 * User: Frings
 * Date: 2016/8/29
 * Time: 10:19
 */

namespace app\controllers;

use app\librarys\BaseController;
use app\librarys\FileService;
use app\librarys\Tools;
use app\librarys\qcloud_cos\Conf;
use app\librarys\qcloud_cos\Cosapi;
use app\models\Card;
use app\models\CardSale;
use app\models\Institution;
use app\models\Permission;
use app\models\Voucher;
use yii\data\Pagination;
use app\models\Information;
use app\models\Manager;
use Yii;
use yii\helpers\VarDumper;
use yii\rest\ViewAction;


class CardController extends BaseController
{
    public static $voucher_file = 'voucher.xlsx';
    public static $download = 'download';

    /********************卡片模板********************/
    /**
     * 卡片模板管理
     * card-tpl-list
     * @return string
     */
    public function actionCardTplList()
    {
        $page = \Yii::$app->request->get('page', 1);//分页起始页默认为1
        $name = \Yii::$app->request->get('name', '');

        //取得产品总数 -用于分页
        $DataCount = 0;
        $PageSize = 10;

        $DataCount = Card::getCardTplCount($name);
        $list = Card::getCardTplList($page, $PageSize, $name);

        $pagination = new Pagination([
            'defaultPageSize' => $PageSize,
            'totalCount' => $DataCount,
        ]);

        //返回分页、结果、以及传入的参数值
        return $this->render('card-tpl-list', ['pagination' => $pagination, 'list' => $list, 'name' => $name]);
    }

    /**
     * 修改/新增卡片模板
     * card-tpl-part-view
     * @return string
     */
    public function actionCardTplPartView()
    {
        $this->layout = false;

        $id = \Yii::$app->request->post('id');
        $name = \Yii::$app->request->post('name');
        $description = \Yii::$app->request->post('description');

        $integral = \Yii::$app->request->post('integral');
        $check_goods_list = \Yii::$app->request->post('check_goods_list');
        if ($integral == '') {
            $integral = 0;
        }

        $item = Card::getCardTplById($id);

        $goods = null;
        if ($id == '') {
            $goods = Card::getCardTolAllGoods($integral);
        } else {
            $goods = Card::getCardTplGoodsById($id, $integral);
        }

        if ($check_goods_list != null && count($check_goods_list) > 0) {
            for ($i = 0; $i < count($check_goods_list); $i++) {
                for ($j = 0; $j < count($goods); $j++) {
                    if ($check_goods_list[$i]['code'] == $goods[$j]['code']) {
                        $goods[$j]['sort'] = $check_goods_list[$i]['sort'];
                    }
                }
            }
        }

        return $this->render('card-tpl-part-view',
            [
                'item' => $item,
                'name' => $name,
                'description' => $description,
                'goods' => $goods,
                'integral' => $integral
            ]);
    }

    /**
     * 模板详情
     * @return string
     */
    public function actionCardTplPartDetail()
    {
        $this->layout = false;

        $id = \Yii::$app->request->post('id');
        $item = Card::getCardTplById($id);
        $goods = Card::getCardTplGoodsById($id);

        $gs = [];
        foreach ($goods as $good) {
            if ($good['sort'] != null && $good['sort'] != '') {
                array_push($gs, $good);
            }
        }

        return $this->render('card-tpl-part-detail',
            [
                'item' => $item,
                'goods' => $gs
            ]);
    }

    /**
     * 新增/修改卡片模板
     * @return string
     */
    public function actionCardTplSave()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');
        $name = $request->post('name');
        $description = $request->post('description');
        $integral = $request->post('integral');
        $page_image_url = $request->post('page_image_url');

        //转换包含的产品和排序
        $card_tpl_goods = $request->post('card_tpl_goods');
        $card_tpl_goods = json_decode($card_tpl_goods)->list;

        $create_manager_id = Manager::getCurrentManager()['id'];
        //读取上传的图片文件
        if (isset($_FILES['image_file'])) {
            if ($_FILES["image_file"]["error"] == 0) {
                $fileName = Tools::uuid() . '.' . pathinfo($_FILES["image_file"]["name"])['extension'];
                $filePath = $_FILES["image_file"]["tmp_name"];
                $page_image_url = FileService::uploadImage($filePath, $fileName);
            }
        }

        $result = Card::saveCardTpl($id, $name, $description, $integral, $page_image_url, $create_manager_id, $card_tpl_goods);
        return $this->renderJson($result, $result ? 0 : 1, '');
    }

    /**
     * 删除卡片模板card-tpl-del
     * @return string
     */
    public function actionCardTplDel()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');

        $result = Card::delCardTpl($id);
        return $this->renderJson($result, $result ? 0 : 1, '');
    }

    /********************卡片********************/

    /**
     * 卡片列表
     * @return string
     */
    public function actionCardList()
    {
        $currentManager = Manager::getCurrentManager();
        $institutions = null;
        if (Permission::isSystemAdmin()) {
            $institutions = Institution::getAllEnabledListWithHierarchy($currentManager['institution_code']);
        } else {
            $institutions = Institution::getAllEnabledChildren($currentManager['institution_code']);
        }
        $page = \Yii::$app->request->get('page', 1);//分页起始页默认为1
        $card_type = \Yii::$app->request->get('card_type', 'send');
        $name = \Yii::$app->request->get('name', '');
        $voucher = \Yii::$app->request->get('voucher', '');
        $from_institution_code = \Yii::$app->request->get('from_institution_code', '');
        $to_institution_code = \Yii::$app->request->get('to_institution_code', '');
        $startTime = \Yii::$app->request->get('startTime', '');
        $endTime = \Yii::$app->request->get('endTime', '');

        //取得产品总数 -用于分页
        $DataCount = 0;
        $PageSize = 10;

        $dataCount = Card::getCardCount($card_type, $currentManager['id'], $currentManager['institution_code'], $name, $voucher, $from_institution_code, $to_institution_code, $startTime, $endTime);
        $list = Card::getCardList($page, $PageSize, $card_type, $currentManager['id'], $currentManager['institution_code'], $name, $voucher, $from_institution_code, $to_institution_code, $startTime, $endTime);
        foreach ($list as &$item) {
            $statusItems = Voucher::getVoucherStatusCount($item['start_index'], $item['end_index']);
            $item['s1'] = Voucher::getVoucherStatusCountByStatus($statusItems, 1) + Voucher::getVoucherStatusCountByStatus($statusItems, 6);
            $item['s2'] = Voucher::getVoucherStatusCountByStatus($statusItems, 2);
            $item['s3'] = Voucher::getVoucherStatusCountByStatus($statusItems, 3);
            $item['s4'] = Voucher::getVoucherStatusCountByStatus($statusItems, 4);
            $item['s5'] = Voucher::getVoucherStatusCountByStatus($statusItems, 5);
        }


        $pagination = new Pagination([
            'defaultPageSize' => $PageSize,
            'totalCount' => $dataCount,
        ]);

        //返回分页、结果、以及传入的参数值
        return $this->render('card-list',
            [
                'pagination' => $pagination,
                'list' => $list,
                'institutions' => $institutions,
                'name' => $name,
                'voucher' => $voucher,
                'current_institution_code' => $currentManager['institution_code'],
                'current_user_id' => $currentManager['id'],
                'card_type' => $card_type,
                'from_institution_code' => $from_institution_code,
                'to_institution_code' => $to_institution_code,
                'startTime' => $startTime,
                'endTime' => $endTime
            ]);
    }

    /**
     * 发放卡片(新增/修改)
     * @return string
     */
    public function actionCardPartView()
    {
        $this->layout = false;

        $currentManager = Manager::getCurrentManager();
        $institutions = Institution::getInstitutionByParentCode($currentManager['institution_code']);

        //获取发卡机构(管理员发放所有机构，当前机构发放下级机构)
        $to_institutions = null;
        if (Permission::isSystemAdmin()) {
            $to_institutions = Institution::getAllEnabledListWithHierarchy($currentManager['institution_code']);
        } else {
            $to_institutions = Institution::getAllEnabledChildren($currentManager['institution_code']);
        }
        //系统管理员显示卡片模板
        $cardtpls = null;
        if ($currentManager['id'] == '0') {
            $cardtpls = Card::getCardTpls();
        }

        $my_cards = Card::getCardsByInstitutionCode($currentManager['institution_code']);


        $id = \Yii::$app->request->post('id');
        $item = Card::getCardById($id);
        $goods = null;
        if ($id == '') {
            if (Permission::isSystemAdmin()) {
                $goods = Card::getCardTolAllGoods();
            }
        } else {
            //展现小于等于卡价值积分的商品
            $goods = Card::getCardGoodsByIdAndIntegral($id, $item['integral']);
        }
        return $this->render('card-part-view',
            [
                'institution_code' => $currentManager['institution_code'],
                'item' => $item,
                'institutions' => $institutions,
                'to_institutions' => $to_institutions,
                'cardtpls' => $cardtpls,
                'my_cards' => $my_cards,
                'goods' => $goods,
                'current_user_id' => $currentManager['id']
            ]);
    }

    /**
     * 查看卡片明细
     * @return string
     */
    public function actionCardPartDetail()
    {
        $this->layout = false;

        $currentManager = Manager::getCurrentManager();
        $institutions = Institution::getInstitutionByParentCode($currentManager['institution_code']);

        $id = \Yii::$app->request->post('card_id');
        $item = Card::getCardById($id);
        if ($item != null) {
            $from_institution = Institution::getInstitutionByCode($item['from_institution_code']);
            if ($from_institution != null) {
                $item['from_institution_name'] = $from_institution['name'];
            }
            $to_institution = Institution::getInstitutionByCode($item['to_institution_code']);
            if ($to_institution != null) {
                $item['to_institution_name'] = $to_institution['name'];
            }
        }
        $goods = Card::getCardGoodsById($id);


        return $this->render('card-part-detail',
            [
                'institution_code' => $currentManager['institution_code'],
                'item' => $item,
                'institutions' => $institutions,
                'goods' => $goods,
                'current_user_id' => $currentManager['id']
            ]);

    }

    /**
     * 根据卡片模板id获取卡片模板信息
     * @return string
     */
    public function actionGetCardTplHandler()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');
        $cardTpl = Card::getCardTplById($id);

        return $this->renderJson($cardTpl, 0, '');
    }

    /**
     * 根据卡片id获取卡片信息
     * @return string
     */
    public function actionGetCardHandler()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');
        $card = Card::getCardById($id);

        //获取最后一次发放的单证号
        $lastCard = Card::getLastCardSend($card['to_institution_code'], $card['start_index'], $card['end_index']);
        if ($lastCard == null) {
            $card['last_index'] = $card['start_index'];
        } else {
            if ($card['end_index'] == $lastCard['end_index']) {
                $card['last_index'] = $lastCard['end_index'];
            } else {
                $card['last_index'] = $lastCard['end_index'] + 1;
            }
        }
        return $this->renderJson($card, 0, '');
    }

    /**
     * 通过模板获取产品
     * @return string
     */
    public function actionCardTplPartViewGoods()
    {
        $this->layout = false;

        $id = \Yii::$app->request->post('id');
        $goods = Card::getCardTplGoodsById($id);

        return $this->render('card-part-view-goods', ['goods' => $goods]);
    }


    /**
     * 通过我的卡片获取产品
     * @return string
     */
    public function actionCardPartViewGoods()
    {
        $this->layout = false;

        $id = \Yii::$app->request->post('id');
        $integral = \Yii::$app->request->post('integral');
        $goods = Card::getCardGoodsByIdAndIntegral($id, $integral);

        return $this->render('card-part-view-goods', ['goods' => $goods]);
    }

    /**
     * 根据积分筛选卡片产品
     * @return string
     */
    public function actionCardPartViewGoodsIntetral()
    {
        $this->layout = false;

        $id = \Yii::$app->request->post('id');
        $integral = \Yii::$app->request->post('integral');
        $list = \Yii::$app->request->post('list');

        $goods = Card::getCardGoodsById($id);

        if ($list != null && count($list)) {
            foreach ($list as $l) {
                foreach ($goods as &$good) {
                    if ($good['code'] == $l['code']) {
                        $good['goods_code'] = $l['code'];
                        $good['sort'] = $l['sort'];
                    }
                }
            }
        }

        foreach ($goods as $key => $row) {
            $num1[$key] = $row ['sort'];
            $num2[$key] = $row ['selling_price'];
        }
        array_multisort($num1, SORT_DESC, $num2, SORT_DESC, $goods);

        $garray = [];

        $c = count($goods);
        for ($i = 0; $i < $c; $i++) {
            if ($goods[$i]['sort'] != null || $goods[$i]['selling_price'] <= $integral) {
                array_push($garray, $goods[$i]);
            }
        }

        return $this->render('card-part-view-goods', ['goods' => $garray]);
    }


    /**
     * 检查单证是否在同一卡片内
     * @return string
     */
    public function actionCheckCardVoucherHandler()
    {
        $currentManager = Manager::getCurrentManager();

        $request = \Yii::$app->request;
        $card_id = $request->post('card_id');
        $start_index = $request->post('start_index');
        $end_index = $request->post('end_index');

        $card = Card::getCardById($card_id);
        if ($card != null) {
            $index_array = [];
            $index_out = '';
            for ($i = 0; $i < $end_index - $start_index + 1; $i++) {
                array_push($index_array, $start_index + $i);
            };
            if ($index_array != null && count($index_array)) {
                foreach ($index_array as $index) {
                    if ($index < $card['start_index'] || $index > $card['end_index']) {
                        $index_out = $index_out . $index . ',';
                    }
                }

                if ($index_out != '') {
                    return $this->renderJson(null, 1, '下列单证号不在该卡片内:' . substr($index_out, 0, strlen($index_out) - 1));
                }
                return $this->renderJson(null, 0, '单证号在该卡片内');

            } else {
                return $this->renderJson(null, 1, '请输入正确的单证起始号');
            }
        }
        return $this->renderJson(null, 1, '无卡片数据');
    }


    /**
     * 保存卡片信息
     * @return string
     * card-save-handler
     */
    public function actionCardSaveHandler()
    {
        $currentManager = Manager::getCurrentManager();

        $request = \Yii::$app->request;
        $id = $request->post('id');
        $name = $request->post('name');
        $description = $request->post('description');
        $start_index = $request->post('start_index');
        $end_index = $request->post('end_index');
        $from_institution_code = $currentManager['institution_code'];
        $to_institution_code = $request->post('to_institution_code');
        $integral = $request->post('integral');
        $create_manager_id = $currentManager['id'];
        $activationVoucher = $request->post('activationVoucher');
        $goodslist = $request->post('goodslist');


        $isSystemAdmin = Permission::isSystemAdmin();
        if (!$isSystemAdmin) {
            //判断是否发卡给下级机构，不是下级机构不能发卡
            $isUnder = Institution::isUnderInstitution($from_institution_code, $to_institution_code);
            if ($isUnder == false) {
                return $this->renderJson(null, 1, '收卡机构不是直属下级机构，不能新增或修改');
            }
        }

        $result = Card::saveCard($isSystemAdmin, $id, $name, $description, $start_index,
            $end_index, $from_institution_code, $to_institution_code,
            $integral, $create_manager_id, $goodslist);


        //是否要求激活
        if ($activationVoucher == 'true') {
            Voucher::updateVoucherStatus($start_index, $end_index, 2);
        }

        if ($result['status'] == 0) {
            return $this->renderJson(null, 0, '执行成功');
        }

        return $this->renderJson(null, 1, $result['message']);
    }

    /**
     * 获取卡片单证
     * @return string
     */
    public function actionCardPartViewVoucher()
    {
        $this->layout = false;

        $currentManager = Manager::getCurrentManager();
        $current_institution_code = $currentManager['institution_code'];
        $request = \Yii::$app->request;
        $card_id = $request->post('card_id');

        $list = Card::getVoucherByCardId($card_id);
        return $this->render('card-part-view-voucher',
            [
                'card_id' => $card_id,
                'list' => $list,
                'current_institution_code' => $current_institution_code,
                'current_user_id' => $currentManager['id']
            ]);
    }

    /**
     * 激活单证
     * @return string
     */
    public function actionActivateVoucher()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');

        $result = Voucher::activateVoucher($id);

        if ($result['status'] == 0) {
            return $this->renderJson(null, 0, '执行成功');
        }
        return $this->renderJson(null, 1, $result['message']);
    }

    /**
     * 激活卡片内单证
     * @return string
     */
    public function actionActivateCardVoucher()
    {
        $currentManager = Manager::getCurrentManager();

        $request = \Yii::$app->request;
        $card_id = $request->post('card_id');
        $card = Card::getCardById($card_id);
        if ($card != null) {
            if ($currentManager['id'] != 0) {
                if ($card['from_institution_code'] != $currentManager['institution_code']) {
                    return $this->renderJson(null, 1, '该批单证号不属于您的机构');
                }
            }
        } else {
            return $this->renderJson(null, 1, '无此批单证号');
        }

        $result = Card::activateCardVoucher($card_id);

        if ($result['status'] == 0) {
            return $this->renderJson(null, 0, '执行成功');
        }
        return $this->renderJson(null, 1, $result['message']);
    }

    /**
     * 失效单证
     * @return string
     */
    public function actionInvalidateVoucher()
    {
        $currentManager = Manager::getCurrentManager();
        $current_institution_code = $currentManager['institution_code'];
        if ($current_institution_code != 0) {
            return $this->renderJson(null, 1, '你不是系统管理员账户，请使用系统管理员账户登录');
        }

        $request = \Yii::$app->request;
        $id = $request->post('id');

        $result = Voucher::invalidateVoucher($id);

        if ($result['status'] == 0) {
            return $this->renderJson(null, 0, '执行成功');
        }
        return $this->renderJson(null, 1, $result['message']);
    }



    /********************销售名片********************/
    /**
     * 销售名片管理
     * @return string
     */
    public function actionCardSaleList()
    {
        $page = \Yii::$app->request->get('page', 1);//分页起始页默认为1
        $name = \Yii::$app->request->get('name', '');
        $saler = \Yii::$app->request->get('saler', '');
        $voucher = \Yii::$app->request->get('voucher', '');
        $startTime = \Yii::$app->request->get('startTime', '');
        $endTime = \Yii::$app->request->get('endTime', '');

        //取得产品总数 -用于分页
        $DataCount = 0;
        $PageSize = 10;

        $DataCount = CardSale::getCardSaleCount($name, $saler, $voucher, $startTime, $endTime);
        $list = CardSale::getCardSaleList($page, $PageSize, $name, $saler, $voucher, $startTime, $endTime);
        foreach ($list as &$item) {
            $statusItems = Voucher::getVoucherStatusCount($item['start_index'], $item['end_index']);
            $item['s1'] = Voucher::getVoucherStatusCountByStatus($statusItems, 1);
            $item['s2'] = Voucher::getVoucherStatusCountByStatus($statusItems, 2);
            $item['s3'] = Voucher::getVoucherStatusCountByStatus($statusItems, 3);
            $item['s4'] = Voucher::getVoucherStatusCountByStatus($statusItems, 4);
            $item['s5'] = Voucher::getVoucherStatusCountByStatus($statusItems, 5);
        }
        $pagination = new Pagination([
            'defaultPageSize' => $PageSize,
            'totalCount' => $DataCount,
        ]);

        return $this->render('card-sale-list',
            [
                'pagination' => $pagination,
                'list' => $list,
                'name' => $name,
                'saler' => $saler,
                'voucher' => $voucher,
                'startTime' => $startTime,
                'endTime' => $endTime
            ]);
    }

    /**
     *销售名片编辑
     * @return string
     */
    public function actionCardSalePartView()
    {
        $this->layout = false;
        return $this->render('card-sale-part-view');
    }

    /**
     * 保存销售名片
     * @return string
     */
    public function actionCardSaleSaveHandler()
    {
        $currentManager = Manager::getCurrentManager();

        $request = \Yii::$app->request;
        $saler = $request->post('saler');
        $name = $request->post('name');
        $description = $request->post('description');
        $start_index = $request->post('start_index');
        $end_index = $request->post('end_index');

        $result = CardSale::saveCardSale($saler, $name, $description, $start_index, $end_index, $currentManager['id']);
        if ($result == false) {
            return $this->renderJson(null, 1, '服务器错误');
        }

        return $this->renderJson(null, 0, '执行成功');
    }

    /**
     * 删除销售名片
     * @return string
     */
    public function actionCardSaleDelHandler()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');

        $result = CardSale::delCardSale($id);
        if ($result == false) {
            return $this->renderJson(null, 1, '服务器错误');
        }

        return $this->renderJson(null, 0, '执行成功');
    }

    /**
     * 获取卡片单证
     * @return string
     */
    public function actionCardSalePartViewVoucher()
    {
        $this->layout = false;

        $request = \Yii::$app->request;
        $start_index = $request->post('start_index');
        $end_index = $request->post('end_index');

        $list = Voucher::getVoucherByStartEndIndex($start_index, $end_index);
        return $this->render('card-sale-part-view-voucher',
            [
                'list' => $list,
                'start_index' => $start_index,
                'end_index' => $end_index
            ]);
    }

    /**
     * 根据卡片id导出单证excel
     * @return string
     */
    public function actionExportVoucherByCardidHandler()
    {
        $currentManager = Manager::getCurrentManager();

        $request = \Yii::$app->request;
        $card_id = $request->post('card_id');
        $card = Card::getCardById($card_id);
        if ($card != null) {
            if ($currentManager['institution_code'] != '0') {
                if ($card['from_institution_code'] != $currentManager['institution_code']) {
                    return $this->renderJson(null, 1, '该批单证号不属于您的机构');
                }
            }
        } else {
            return $this->renderJson(null, 1, '无此批单证号');
        }

        $start_index = $card['start_index'];
        $end_index = $card['end_index'];
        $list = Voucher::getVoucherByStartEndIndex($start_index, $end_index);
        $objPHPExcel = \PHPExcel_IOFactory::load(self::$voucher_file);

        $i = 2;
        foreach ($list as $item) {

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $i, $item['voucher']);
            switch ($item['status']) {
                case 0:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '未使用');
                    break;
                case 1:
                case 6:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '已绑定');
                    break;
                case 2:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '已激活');
                    break;
                case 3:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '已使用');
                    break;
                case 4:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '失效');
                    break;
                case 5:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '过期');
                    break;
            }

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $i, $item['name']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $i, $item['phone']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $i, $item['create_datetime']);


            $i++;

        }
        // 给当前活动的表设置名称
        //$objActSheet->setTitle('Simple2222');
        //windows下使用该
        $filename = '';
        if (\Yii::$app->params['iswindows']) {
            $filename = self::$download . '\voucher' . time() . '.xlsx';
        } else {
            //Linux下使用
            $filename = self::$download . '//' . 'voucher' . time() . '.xlsx';
        }

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save($filename);

        return $this->renderJson($filename, 0, 0);
    }

    /**
     *根据单证号开始结束导出单证excel
     * @return string
     */
    public function actionExportVoucherHandler()
    {
        $request = \Yii::$app->request;
        $start_index = $request->post('start_index');
        $end_index = $request->post('end_index');
        $list = Voucher::getVoucherByStartEndIndex($start_index, $end_index);
        $objPHPExcel = \PHPExcel_IOFactory::load(self::$voucher_file);

        $i = 2;
        foreach ($list as $item) {

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $i, $item['voucher']);
            switch ($item['status']) {
                case 0:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '未使用');
                    break;
                case 1:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '已绑定');
                    break;
                case 2:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '已激活');
                    break;
                case 3:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '已使用');
                    break;
                case 4:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '失效');
                    break;
                case 5:
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '过期');
                    break;
            }

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $i, $item['name']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $i, $item['phone']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $i, $item['create_datetime']);
            $i++;

        }
        // 给当前活动的表设置名称
        //$objActSheet->setTitle('Simple2222');
        //windows下使用该
        $filename = '';
        if (\Yii::$app->params['iswindows']) {
            $filename = self::$download . '\voucher' . time() . '.xlsx';
        } else {
            //Linux下使用
            $filename = self::$download . '//' . 'voucher' . time() . '.xlsx';
        }

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save($filename);

        return $this->renderJson($filename, 0, 0);
    }


    /**
     * 生成单证号
     */
    public function actionGenVoucher()
    {
        $count = Voucher::getAllVoucherCount();
        $max = Voucher::getMaxVoucher();
        return $this->render('gen-voucher', ['count' => $count, 'max' => $max]);
//        echo 'failed.';
//        exit;
//10143146
//        $pwd = \Yii::$app->request->get('pwd');
//        if ($pwd != 'GOODHOPE505') {
//            return $this->renderJson('error', -1, 'error');
//        }
////        $startIndex = 10132547;
////        $startIndex = 10142547;
//        $startIndex = 10144150;
////        $startIndex = Voucher::getMaxVoucher() + 1;
////        $endIndex = $startIndex + 500;
////        for ($i = $startIndex; $i < $endIndex; $i++) {
////            $id = $i;
////            $token = rand(0, 99999999);
////            $token = str_pad($token, 8, '0', STR_PAD_LEFT);
//////            echo $id . '        ' . $token . '<br>';
////            Voucher::gen($id, $token);
////        }
//        $result = Voucher::gen($startIndex, 500);
//
//        if ($result == true) {
//            return $this->renderJson('ok');
//        } else {
//            return $this->renderJson('failed', -100, 'failed');
//        }
    }

    public function actionGenVoucherForm()
    {
        if (\Yii::$app->request->post()) {
            $pwd = \Yii::$app->request->post('pwd');

            $m = Manager::validatePassword(Manager::getCurrentManager()['account'], $pwd);
            if (empty($m)) {
                throw new \Exception('pwd error');
            }

            $startIndex = \Yii::$app->request->post('startIndex');
            $count = \Yii::$app->request->post('count');
            $result = Voucher::gen($startIndex, $count);
            if ($result == true) {
                return $this->redirect('gen-voucher');
            } else {
                throw new \Exception('gen failed');
            }
        } else {
            throw new \Exception('request error');
        }
    }
}